package com.simp.service;

import com.github.benmanes.caffeine.cache.Cache;
import com.simp.costant.Constant;
import com.simp.page.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author pan.shun
 * @since 2022/3/29 16:55
 */
@Service
@Slf4j
public class CommonService {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private Cache<String, Object> caffeineCache;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public R getEarlyStartTime() {
        @Nullable Object ifPresent = caffeineCache.getIfPresent(Constant.CACHE_KEY.PROJECT_START_TIME);
        if (ifPresent != null) {
            Date date = new Date((Long) ifPresent);
            return R.success(format.format(date));
        } else {
            return R.success();
        }
    }


    public R getAllCacheInfo() {
        Map<String, Object> cacheInfoMap = new ConcurrentHashMap<>();
        ConcurrentMap<String, Object> stringObjectConcurrentMap = caffeineCache.asMap();
        Map<String, Object> redisCacheMap = new HashMap<>();
        Set<String> keys = redisTemplate.keys("*");

        keys.forEach(r -> {
            try {
                Object v = redisTemplate.opsForValue().get(r);
                redisCacheMap.put(r, v);
            } catch (Exception e) {
                log.error("通过KEY获取value 失败, 当前KEY 为 :{}", r);
            }
        });
        keys.forEach(r -> redisCacheMap.put(r, redisTemplate.opsForValue().get(r)));
        cacheInfoMap.put("caffeine_cache", stringObjectConcurrentMap);
        cacheInfoMap.put("redis_cache", redisCacheMap);
        return R.success(cacheInfoMap);
    }
}
